package com.whu.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.whu.UVAProtocol.UVAConnection;
import com.whu.UVAProtocol.UVAServer;
import com.whu.UVAProtocol.UVAServerHandler;
import com.whu.aircraft.*;
import com.whu.service.impl.AircraftService;
import com.whu.service.impl.PictureService;
import com.whu.vo.FlightTaskVO;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;

@RestController
public class AircraftController {

    private final PictureService pictureService;
    private final AircraftService aircraftService;

    @Autowired
    public AircraftController(PictureService pictureService, AircraftService aircraftService) {
        this.pictureService = pictureService;
        this.aircraftService = aircraftService;
    }

    @RequestMapping("/aircraftman/picupdate/{id}")
    public R picUpdate(@PathVariable int id) throws InterruptedException {
        UVAConnection conn = UVAServer.uvaConnections.get(id);
        if(conn!=null){
            LinkedBlockingDeque<String> picMsgQueue = conn.getPicMsgQueue();
            String picPath = picMsgQueue.poll();
            if(picPath!=null){
                String picBase64 = pictureService.imageChangeBase64(picPath);
                return R.ok(picBase64);
            }
        }
        return R.error("no more picture!");
    }
    @RequestMapping("/aircraftman/shot/{id}")
    public void shot(@PathVariable int id){
        //获取channel
        UVAConnection conn = UVAServer.uvaConnections.get(id);
        if(conn!=null) {
            Channel channel = conn.getChannel();
            if(channel!=null){
                UVAServerHandler handler = (UVAServerHandler) channel.pipeline().get("serverHandler");
                ChannelHandlerContext context = channel.pipeline().context(handler);
                //发送拍照请求
                handler.requestShot(context,(byte) id,0);
            }


        }
    }
    @RequestMapping("/aircraftman/getwarning/{id}")
    public R getWarning(@PathVariable int id){
        Aircraft aircraft = UVAServer.uvaConnections.get(id).getAircraft();
        Byte warning = aircraft.getWarnings().poll();
        if(warning==null){
            return R.ok("一切正常！");
        }else if(warning==1){
            return R.error(warning,"电池电量不足！");
        }else if(warning==2){
            return R.error(warning,"即将碰撞！");
        }else if(warning==3){
            return R.error(warning,"GPS信号弱！");
        }else {
            return R.error(15,"预期外的错误");
        }
    }
    @RequestMapping("/aircraftman/getConnectionstate/{id}")
    public R getConnectionState(@PathVariable int id){
        if(UVAServer.uvaConnections.containsKey(id)){
            //正常连接
            return R.ok("连接正常");
        }else{
            //非正常连接
            if (UVAServer.disconnections.containsKey(id)){
                //重连中
                return R.ok("重连中...");
            }else {
                //断线
                return R.ok("连接已断开！");
            }
        }
    }
    @RequestMapping("/aircraftman/getaircraftbyid/{id}")
    public Aircraft getAircraftById(@PathVariable int id){
        return aircraftService.getAircraftById(id);
    }
    @RequestMapping("/aircraftman/sendctrlcmd/{uvaId}/{direction}")
    public R sendCtrlCommand(@PathVariable("uvaId") Integer uvaId, @PathVariable("direction") Byte direction){
        //获取channel
        UVAConnection conn = UVAServer.uvaConnections.get(uvaId);
        if(conn!=null) {
            Channel channel = conn.getChannel();
            if(channel!=null){
                UVAServerHandler handler = (UVAServerHandler) channel.pipeline().get("serverHandler");
                ChannelHandlerContext context = channel.pipeline().context(handler);
                //发送
                ControlCommand command = new ControlCommand();
                command.setDirection(direction);
                handler.sendControlCommand(context,(byte)(int)uvaId,command);
                return R.ok();
            }else {
                return R.error("该无人机网络连接异常！");
            }
        }else {
            return R.error("没有该无人机！");
        }
    }
    /**
     * @Description :返回地址为id的无人机信息
     * @Param [id]
     * @Return com.whu.aircraft.Aircraft
     * @Author chengeng
     * @Date 2022/2/17 16:35
     **/
    @RequestMapping("/aircraftman/updateaircraftinfo/{id}")
    public Aircraft updateAircraftInfo(@PathVariable Integer id){
        UVAConnection conn = UVAServer.uvaConnections.get(id);
        if(conn!=null){
            return conn.getAircraft();
        }else{
            conn = UVAServer.disconnections.get(id);
            if(conn!=null){
                return conn.getAircraft();
            }
        }
        return null;
    }
    /**
     * @Description 切换id为uvaId的无人机控制模式，mode为0 服务器放弃无人机控制权，为1服务器强制获取无人机控制权
     * @Param [uvaId, mode]
     * @Return com.whu.aircraft.R
     * @Author chengeng
     * @Date 2022/2/16 15:15
     **/
    @RequestMapping("/aircraftman/controllmode/{uvaId}/{mode}")
    public R getOrAbandonController( @PathVariable("uvaId") Integer uvaId, @PathVariable("mode") Byte mode){
        System.out.println(uvaId+" "+mode);
        //获取channel
        UVAConnection conn = UVAServer.uvaConnections.get(uvaId);
        if(conn!=null) {
            Channel channel = conn.getChannel();
            if(channel!=null){
                UVAServerHandler handler = (UVAServerHandler) channel.pipeline().get("serverHandler");
                ChannelHandlerContext context = channel.pipeline().context(handler);
                //发送
                handler.switchControlMode(context, (byte) (int) uvaId, mode);
                return R.ok();
            }else {
                return R.error("该无人机网络连接异常！");
            }

        }else {
            return R.error("没有该无人机！");
        }
    }
    @RequestMapping("/aircraftman/aircraft")
    public List<Aircraft> getAircraft(){
        return aircraftService.getAircraft();
    }
    @RequestMapping("/aircraftman/assigntask")
    public R assignTask(@RequestBody FlightTaskVO taskVO) throws ParseException, JsonProcessingException {
        //UVAServerHandler serverHandler = (UVAServerHandler) Main.uvaServer.getInitializer().getPipeline().get("serverHandler");
        //System.out.println(serverHandler);
        if(taskVO.getAircraftID()==null){
            return R.error("请检查无人机id是否正确！！！");
        }
        int id = taskVO.getAircraftID();
        UVAConnection conn = UVAServer.uvaConnections.get(id);
        Channel channel = conn.getChannel();
        if(channel!=null){
            UVAServerHandler handler = (UVAServerHandler) channel.pipeline().get("serverHandler");
            ChannelHandlerContext context = channel.pipeline().context(handler);
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            FlightTask task = new FlightTask();
            task.setFlightTaskName(taskVO.getFlightTaskName());
            task.setCreateTime(dateFormat.parse(taskVO.getCreateTime()));
            task.setUpdateTime(dateFormat.parse(taskVO.getUpdateTime()));
            task.setDefaultHeight(taskVO.getFlightTaskDefaultHeight());
            task.setDefaultVelocity(taskVO.getFlightTaskDefaultVelocity());
            ArrayList<RoutePoint> routes = new ArrayList<>();
            int pathLen = taskVO.getFlightTaskHeight().length;
            for(int i=0;i<pathLen;i++){
                RoutePoint rp = new RoutePoint();
                rp.setHeight(taskVO.getFlightTaskHeight()[i]);
                rp.setVelocity(taskVO.getFlightTaskVelocity()[i]);
                rp.setLongitude(taskVO.getFlightTaskPath()[i][0]);
                rp.setLatitude(taskVO.getFlightTaskPath()[i][1]);
                routes.add(rp);
            }
            task.setRoute(routes);
            task.route2Json();
            conn.getAircraft().setTask(task);
            handler.sendRouteInfo(context, (byte) id);
            return R.ok("飞行任务分配完毕");
        }else{
            return R.error("该无人机网络连接异常");
        }

    }

}
